package com.ykt.controller;

import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.ykt.model.CameraMarket;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@ControllerBind(controllerKey="/cameraMarket")
public class CameraMarketController extends BaseController<CameraMarket> {

	public CameraMarketController() {
		super(CameraMarket.class);
	}
	
	public void findCamera() {
		Integer marketId = getParaToInt("marketId", -1);
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("m.id", marketId.toString());
		
		int page = getParaToInt("page", 1);
        int rows = this.getParaToInt("rows", 20);
        try {
            Page<CameraMarket> date = modelClass.newInstance().pageFindModel(page, rows, paramMap);
            rendDataGrid(date);
        } catch (Exception e) {
            log.error(e);
            rendJson(false, e.getMessage());
        }
	}
	
	public void savaCamera(){
		String marketId = this.getPara("marketId");
		String cameraId = this.getPara("cameraId");
		
		String sql = "SELECT * FROM camera_market c WHERE c.camera_id = " + cameraId + " AND c.market_id = " + marketId;
		CameraMarket market = null;
		market = CameraMarket.dao.findFirst(sql);
		
		String msg = "此摄像头已经存在！";
		Integer id = null;
		if (market == null) {
			market = new CameraMarket();
			market.set("market_id", marketId);
			market.set("camera_id", cameraId);
			market.save();
			msg = "保存成功！";
			id = market.getInt("id");
		}
		rendJson(true, msg, id, new Random().nextLong());
	}
	
	public void deleteCamera(){
		String id = this.getPara("id");
		CameraMarket.dao.deleteById(id);
		String msg = "删除成功！";
		id = null;
		rendJson(true, msg, id, new Random().nextLong());
	}

}
